package com.lxf.project;

import com.lxf.project.inteface.AsyncService;
import org.apache.dubbo.rpc.AsyncContext;
import org.apache.dubbo.rpc.RpcContext;

import java.util.concurrent.CompletableFuture;

public class AsyncServiceImpl implements AsyncService {
    @Override
    public CompletableFuture<String> sayHello(String name) {
        RpcContext savedContext = RpcContext.getContext();
        // 建议为supplyAsync提供自定义线程池，避免使用JDK公用线程池
        return CompletableFuture.supplyAsync(() -> {
//            System.out.println(savedContext.getAttachment("consumer-key1"));
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "async response from provider.";
        });

    }

    @Override
    public String sayHello1(String name) {
        final AsyncContext asyncContext = RpcContext.startAsync();
        RpcContext context = RpcContext.getContext();

        new Thread(() -> {
            // 如果要使用上下文，则必须要放在第一句执行
            asyncContext.signalContextSwitch();
            try {
                // 写回响应
                asyncContext.write("Hello " + name + ", response from provider.");
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }).start();
        return context.getRemoteHost();
    }
}
